package disk;

/**
 * 磁盘块
 * 
 * @author vincent
 * 
 */
public class Block {

	/**
	 * 每个磁盘块64字节
	 */
	private byte[] bytes = new byte[64];

	/**
	 * 构造函数
	 */
	public Block() {
		// 清空盘块数据
		clear();
	}

	/**
	 * 设置盘块第index字节的值
	 * 
	 * @param index
	 * @param value
	 */
	public void setByte(int index, byte value) {
		bytes[index] = value;
	}

	/**
	 * 获取盘块第index字节的数据
	 * 
	 * @return
	 */
	public byte getByte(int index) {
		return bytes[index];
	}

	/**
	 * 获取盘块某一段的数据
	 * 
	 * @param from
	 * @param to
	 * @return
	 */
	public byte[] getBytes(int from, int to) {
		int length = to - from + 1;
		byte[] data = new byte[length];
		int index = 0;
		for (int i = from; i <= to; i++) {
			data[index++] = bytes[i];
		}
		return data;
	}

	/**
	 * 获取整个盘块的数据
	 * 
	 * @return
	 */
	public byte[] getBytes() {
		return bytes;
	}

	/**
	 * 设置整个盘块的数据
	 * 
	 * @param bytes
	 */
	public void setBytes(byte[] bytes) {
		this.bytes = bytes;
	}

	/**
	 * 根据内容的字节长度判断所需要的盘块数量
	 * 
	 * @param allocateBytes
	 * @return
	 */
	public static int getBlockLength(int allocateBytes) {
		int blockLength = allocateBytes / 64;
		if (allocateBytes % 64 != 0) { // 剩下内容不足一个盘块的也占用一个盘块
			blockLength++;
		}
		return blockLength;
	}

	/**
	 * 清空盘块数据
	 */
	public void clear() {
		for (int i = 0; i < bytes.length; i++) {
			bytes[i] = 0;
		}
	}

	/**
	 * 输出盘块的内容
	 */
	public void print() {
		for (int i = 0; i < bytes.length; i++) {
			System.out.println(i + "   " + bytes[i] + "   " + (char) bytes[i]);

		}
	}

}
